<template>
  <div class="practice">
    <div class="header">
      <div class="header-left">
        <div class="logo">
          <img 
            src="/logo.svg" 
            alt="Logo" 
            class="logo-img" 
            @error="handleLogoError" 
            @load="logoLoaded = true"
            v-show="logoLoaded"
          />
          <span class="logo-text" v-show="!logoLoaded">面试题</span>
        </div>
        <h2>开始刷题</h2>
      </div>
      <button class="btn btn-secondary" @click="goBack">返回题库</button>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-icon">✨</div>
      <div class="loading-text">正在加载题目...</div>
    </div>
    
    <div v-else-if="questions.length === 0" class="no-data">
      <div class="no-data-icon">📝</div>
      <div class="no-data-text">暂无题目，请先生成模拟题</div>
      <button class="btn btn-primary" @click="goBack">返回题库</button>
    </div>

    <div v-else-if="currentQuestion" class="practice-wrapper">
      <div class="practice-content">
        <!-- 题目进度 -->
        <div class="progress-bar">
          <div class="progress-info">
            <span>进度 {{ answeredCount }} / {{ totalQuestions }}</span>
            <span v-if="isSubmitted" class="submit-info">已交卷</span>
          </div>
          <div class="progress-line">
            <div 
              class="progress-fill" 
              :style="{ width: (totalQuestions > 0 ? (answeredCount / totalQuestions * 100) : 0) + '%' }"
            ></div>
          </div>
        </div>

        <!-- 题目概述 -->
        <div v-if="currentQuestion.overview" class="overview-section">
          <div class="overview-label">题目概述：</div>
          <div class="overview-content">
            <MarkdownRenderer :content="currentQuestion.overview" />
          </div>
        </div>

        <!-- 题目内容 -->
        <div class="question-section">
          <div class="question-title">{{ currentQuestion.question }}</div>
          
          <!-- 选项列表 -->
          <div class="options-section">
            <div
              v-for="(option, index) in currentQuestion.options"
              :key="index"
              class="option-item"
              :class="{
                'selected': selectedOption === option.optionKey && !isSubmitted,
                'correct': isSubmitted && option.isCorrect,
                'wrong': isSubmitted && selectedOption === option.optionKey && !option.isCorrect,
                'disabled': isSubmitted
              }"
              @click="selectOption(option.optionKey)"
            >
              <div class="option-radio">
                <div 
                  v-if="selectedOption === option.optionKey || (isSubmitted && option.isCorrect)"
                  class="radio-inner"
                  :class="{
                    'correct': isSubmitted && option.isCorrect,
                    'wrong': isSubmitted && selectedOption === option.optionKey && !option.isCorrect,
                    'selected': selectedOption === option.optionKey && !isSubmitted
                  }"
                ></div>
              </div>
              <span class="option-key">{{ option.optionKey }}.</span>
              <span class="option-value">{{ option.optionValue }}</span>
            </div>
          </div>

          <!-- 答案和解析（仅交卷后显示） -->
          <div v-if="isSubmitted && showAnswer" class="answer-section">
            <div class="answer-result" :class="isCorrect ? 'correct' : 'wrong'">
              <div class="result-icon">{{ isCorrect ? '✓' : '✗' }}</div>
              <div class="result-text">
                <div class="result-title">{{ isCorrect ? '回答正确！' : '回答错误' }}</div>
                <div class="result-answer">正确答案：{{ currentQuestion.answer }}</div>
              </div>
            </div>
            
            <div v-if="currentQuestion.explanation" class="explanation-section">
              <div class="explanation-label">解析：</div>
              <div class="explanation-content">{{ currentQuestion.explanation }}</div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button 
              v-if="!isSubmitted && showAnswer && currentQuestionIndex < totalQuestions - 1" 
              class="btn btn-primary" 
              @click="nextQuestion"
            >
              下一题
            </button>
            <button 
              v-if="!isSubmitted && showAnswer && currentQuestionIndex >= totalQuestions - 1"
              class="btn btn-submit" 
              @click="submitPaper"
            >
              交卷
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧答题卡 -->
      <div class="answer-card">
        <div class="card-header">
          <h3>答题卡</h3>
          <div v-if="isSubmitted" class="score-info">
            <span>得分：{{ correctCount }} / {{ totalQuestions }}</span>
          </div>
        </div>
        <div class="card-content">
          <div class="question-grid">
            <div
              v-for="(record, index) in answerRecords"
              :key="index"
              class="question-number"
              :class="{
                'current': currentQuestionIndex === index,
                'answered': record.isCompleted,
                'correct': record.isCompleted && record.isCorrect === true,
                'wrong': record.isCompleted && record.isCorrect === false && isSubmitted
              }"
              @click="jumpToQuestion(index)"
            >
              <span class="number">{{ index + 1 }}</span>
              <span v-if="isSubmitted && record.isCompleted && record.isCorrect === false" class="wrong-mark">❌</span>
            </div>
          </div>
        </div>
        <div v-if="!isSubmitted" class="card-footer">
          <div class="legend">
            <div class="legend-item">
              <span class="legend-color current"></span>
              <span>当前</span>
            </div>
            <div class="legend-item">
              <span class="legend-color answered"></span>
              <span>已答</span>
            </div>
            <div class="legend-item">
              <span class="legend-color not-answered"></span>
              <span>未答</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import api from '@/utils/api'
import type { PracticeQuestionVO } from '@/types/interview'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const questions = ref<PracticeQuestionVO[]>([])
const currentQuestionIndex = ref(0)
const selectedOption = ref<string | null>(null)
const showAnswer = ref(false)
const isCorrect = ref(false)
const isSubmitted = ref(false) // 是否已交卷

// 答题记录
interface AnswerRecord {
  questionIndex: number
  userAnswer: string | null
  isCorrect: boolean | null // null表示未答题，true表示答对，false表示答错
  isCompleted: boolean // 是否已完成（点击了下一题）
}

const answerRecords = ref<AnswerRecord[]>([])

// 已答题数量（点击了下一题的题目数量）
const answeredCount = computed(() => {
  return answerRecords.value.filter(r => r.isCompleted).length
})

// 答对数量（已完成且答对的题目数量）
const correctCount = computed(() => {
  return answerRecords.value.filter(r => r.isCompleted && r.isCorrect === true).length
})

// Logo相关
const logoLoaded = ref(false)
const handleLogoError = () => {
  logoLoaded.value = false
}

const currentQuestion = computed(() => {
  if (questions.value.length === 0) return null
  return questions.value[currentQuestionIndex.value]
})

const totalQuestions = computed(() => questions.value.length)

const loadQuestions = async () => {
  loading.value = true
  
  try {
    const interviewQuestionId = route.query.interviewQuestionId 
      ? (route.query.interviewQuestionId as string)
      : undefined
    
    const response = await api.get('/practice/questions', {
      params: interviewQuestionId ? { interviewQuestionId } : {}
    })
    
    if (response.data.code === 200) {
      questions.value = response.data.data || []
      if (questions.value.length > 0) {
        currentQuestionIndex.value = 0
        initAnswerRecords()
        resetQuestionState()
      }
    } else {
      alert('加载题目失败：' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载题目失败:', error)
    alert('加载题目失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const selectOption = (optionKey: string) => {
  if (isSubmitted.value) return // 已交卷不能选择
  selectedOption.value = optionKey
  // 选择答案后自动提交
  submitAnswer()
}

const initAnswerRecords = () => {
  answerRecords.value = questions.value.map((_, index) => ({
    questionIndex: index,
    userAnswer: null,
    isCorrect: null,
    isCompleted: false
  }))
}

const submitAnswer = () => {
  if (!selectedOption.value || !currentQuestion.value || isSubmitted.value) return
  
  showAnswer.value = true
  isCorrect.value = selectedOption.value === currentQuestion.value.answer
  
  // 记录答案
  const record = answerRecords.value[currentQuestionIndex.value]
  if (record) {
    record.userAnswer = selectedOption.value
    record.isCorrect = isCorrect.value
  }
}

const nextQuestion = () => {
  // 标记当前题目为已完成
  const record = answerRecords.value[currentQuestionIndex.value]
  if (record && record.userAnswer !== null) {
    record.isCompleted = true
    // 如果还没有设置 isCorrect，现在设置
    if (record.isCorrect === null && currentQuestion.value) {
      record.isCorrect = record.userAnswer === currentQuestion.value.answer
    }
  }
  
  // 跳转到下一题
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
    resetQuestionState()
  }
}

const submitPaper = () => {
  if (!confirm('确定要交卷吗？交卷后将无法修改答案。')) return
  
  // 标记最后一题为已完成（如果用户已经选择了答案）
  const record = answerRecords.value[currentQuestionIndex.value]
  if (record && record.userAnswer !== null && !record.isCompleted) {
    record.isCompleted = true
    if (record.isCorrect === null && currentQuestion.value) {
      record.isCorrect = record.userAnswer === currentQuestion.value.answer
    }
  }
  
  isSubmitted.value = true
  // 显示当前题目的答案和解析
  if (currentQuestion.value && selectedOption.value) {
    showAnswer.value = true
    isCorrect.value = selectedOption.value === currentQuestion.value.answer
  }
}

const jumpToQuestion = (index: number) => {
  if (index >= 0 && index < questions.value.length) {
    currentQuestionIndex.value = index
    resetQuestionState()
    // 如果已交卷，显示该题的答案
    if (isSubmitted.value) {
      const record = answerRecords.value[index]
      if (record && record.userAnswer) {
        selectedOption.value = record.userAnswer
        showAnswer.value = true
        isCorrect.value = record.isCorrect === true
      }
    }
  }
}

const resetQuestionState = () => {
  // 如果已交卷，恢复该题的答案显示
  if (isSubmitted.value) {
    const record = answerRecords.value[currentQuestionIndex.value]
    if (record && record.userAnswer) {
      selectedOption.value = record.userAnswer
      showAnswer.value = true
      isCorrect.value = record.isCorrect === true
      return
    }
  }
  selectedOption.value = null
  showAnswer.value = false
  isCorrect.value = false
}

const goBack = () => {
  router.push({ name: 'InterviewQuestionList' })
}

onMounted(() => {
  loadQuestions()
})
</script>

<style scoped>
.practice {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 40px);
}

.practice-wrapper {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  height: 40px;
}

.logo-img {
  max-height: 40px;
  max-width: 120px;
  object-fit: contain;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  letter-spacing: 1px;
}

.header h2 {
  margin: 0;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-secondary {
  background-color: #909399;
  color: white;
}

.btn-secondary:hover {
  background-color: #a6a9ad;
}

.loading-container {
  text-align: center;
  padding: 60px 40px;
}

.loading-icon {
  font-size: 64px;
  margin-bottom: 20px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}

.loading-text {
  font-size: 18px;
  color: #606266;
}

.no-data {
  text-align: center;
  padding: 80px 40px;
}

.no-data-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.no-data-text {
  font-size: 16px;
  color: #909399;
  margin-bottom: 24px;
}

.practice-content {
  flex: 1;
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.progress-bar {
  margin-bottom: 24px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.submit-info {
  color: #67c23a;
  font-weight: 600;
}

.progress-line {
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #66b1ff);
  transition: width 0.3s;
}

.overview-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.overview-label {
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.overview-content {
  color: #606266;
  line-height: 1.6;
}

/* 确保 Markdown 渲染器在 overview-content 中的样式正确 */
.overview-content :deep(.markdown-content) {
  color: #606266;
}

.question-section {
  margin-top: 24px;
}

.question-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
  line-height: 1.6;
}

.options-section {
  margin-bottom: 24px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: white;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover:not(.disabled) {
  border-color: #409eff;
  background: #f0f9ff;
}

.option-item.selected {
  border-color: #67c23a;
  background: #f0f9ff;
}

.option-item.selected.correct,
.option-item.correct {
  border-color: #67c23a;
  background: #f0f9ff;
}

.option-item.selected.wrong,
.option-item.wrong {
  border-color: #f56c6c;
  background: #fef0f0;
}

/* 确保未提交时，selected状态覆盖其他状态 */
.option-item.selected:not(.disabled) {
  border-color: #67c23a !important;
  background: #f0f9ff !important;
}

.option-item.disabled {
  cursor: not-allowed;
}

.option-radio {
  width: 20px;
  height: 20px;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.option-item.selected .option-radio {
  border-color: #67c23a;
}

.option-item.correct .option-radio {
  border-color: #67c23a;
}

.option-item.wrong .option-radio {
  border-color: #f56c6c;
}

.radio-inner {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #67c23a;
}

.radio-inner.selected {
  background: #67c23a;
}

.radio-inner.correct {
  background: #67c23a;
}

.radio-inner.wrong {
  background: #f56c6c;
}

.option-key {
  font-weight: 600;
  color: #409eff;
  margin-right: 8px;
  min-width: 24px;
}

.option-value {
  color: #606266;
  flex: 1;
  line-height: 1.5;
}

.answer-section {
  margin-top: 24px;
  padding: 20px;
  border-radius: 8px;
}

.answer-result {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.answer-result.correct {
  background: #f0f9ff;
  border-left: 4px solid #67c23a;
}

.answer-result.wrong {
  background: #fef0f0;
  border-left: 4px solid #f56c6c;
}

.result-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
  flex-shrink: 0;
}

.answer-result.correct .result-icon {
  background: #67c23a;
  color: white;
}

.answer-result.wrong .result-icon {
  background: #f56c6c;
  color: white;
}

.result-text {
  flex: 1;
}

.result-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}

.answer-result.correct .result-title {
  color: #67c23a;
}

.answer-result.wrong .result-title {
  color: #f56c6c;
}

.result-answer {
  font-size: 16px;
  color: #606266;
}

.explanation-section {
  padding: 16px;
  background: #f6ffed;
  border-left: 4px solid #52c41a;
  border-radius: 8px;
}

.explanation-label {
  font-weight: 600;
  color: #52c41a;
  margin-bottom: 8px;
}

.explanation-content {
  color: #606266;
  line-height: 1.6;
}

.action-buttons {
  margin-top: 24px;
  text-align: center;
}

.action-buttons .btn {
  min-width: 120px;
  padding: 12px 32px;
  font-size: 16px;
}

.btn-submit {
  background-color: #67c23a;
  color: white;
}

.btn-submit:hover {
  background-color: #85ce61;
}

.btn:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

/* 答题卡样式 */
.answer-card {
  width: 280px;
  flex-shrink: 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.card-header h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.score-info {
  font-size: 14px;
  color: #606266;
}

.score-info span {
  color: #67c23a;
  font-weight: 600;
}

.card-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
}

.question-number {
  position: relative;
  width: 40px;
  height: 40px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.question-number:hover {
  border-color: #409eff;
  transform: translateY(-2px);
}

.question-number.current {
  border-color: #409eff;
  background: #ecf5ff;
  font-weight: 600;
}

.question-number.answered {
  border-color: #67c23a;
  background: #f0f9ff;
  color: #67c23a;
}

.question-number.correct {
  border-color: #67c23a;
  background: #f0f9ff;
}

.question-number.wrong {
  border-color: #f56c6c;
  background: #fef0f0;
}

.question-number .number {
  font-size: 14px;
  font-weight: 500;
}

.question-number .wrong-mark {
  position: absolute;
  top: -4px;
  right: -4px;
  font-size: 16px;
  line-height: 1;
}

.card-footer {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #f5f7fa;
}

.legend {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #606266;
}

.legend-color {
  width: 16px;
  height: 16px;
  border: 2px solid #e4e7ed;
  border-radius: 4px;
}

.legend-color.current {
  border-color: #409eff;
  background: #ecf5ff;
}

.legend-color.answered {
  border-color: #67c23a;
  background: #f0f9ff;
}

.legend-color.not-answered {
  background: white;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .practice-wrapper {
    flex-direction: column;
  }

  .answer-card {
    width: 100%;
    position: static;
    max-height: none;
  }

  .question-grid {
    grid-template-columns: repeat(10, 1fr);
  }
}
</style>

